import { Inject, Injectable } from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';

@Injectable()
export class StatisticService {
  @Inject(PrismaService)
  private readonly prisma: PrismaService;

  async getMeetingList(startTime, endTime) {
    return await this.prisma.meeting.findMany({
      where: {
        start_time: {
          gte: startTime && new Date(startTime),
        },
        end_time: {
          lte: endTime && new Date(endTime),
        },
      },
    });
  }

  async bookingCount(startTime: string, endTime: string, type: string) {
    const meetingList = await this.getMeetingList(startTime, endTime);

    const colunm = type === 'user' ? 'userId' : 'roomId';
    const colunm_name = type === 'user' ? 'username' : 'name';

    const resList = meetingList.reduce((acc, cur) => {
      acc[cur[colunm]] = acc[cur[colunm]] ? acc[cur[colunm]] + 1 : 1;
      return acc;
    }, {});

    const MapList = await this.prisma[type].findMany({
      where: {
        id: {
          in: Object.keys(resList).map((item) => +item),
        },
      },
      select: {
        id: true,
        [colunm_name]: true,
      },
    });

    return MapList.map((item) => {
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      item.count = resList[item.id];
      return item;
    });
  }
}
